#include "Sock.hpp"
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

using namespace std;

void Usage(string proc)
{
    cout << "Usage:" << proc << endl;
}

void *HandlerHttpRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self());

#define SIZE 1024 * 10
    char buffer[SIZE];
    memset(&buffer, 0, sizeof(buffer));

    //从sock里读取内容放到buffer
    ssize_t s = recv(sock, buffer, sizeof(buffer), 0);
    if (s > 0)
    {
        buffer[s] = 0;
        cout << buffer << endl;

        //响应部分
        // string http_response = "http/1.0 200 OK\n";   //状态行
        // http_response += "Content-Type:text/plain\n"; // text/plain表示正文是普通文本
        // http_response += "\n";                        //空行
        // http_response = "hello world!";               //正文
        // send(sock, http_response.c_str(), http_response.size(), 0);

        string html_file = WWWROOT;
        html_file += HOME_PAGE;
        struct stat st;
        // stat可以获取文件属性，属性信息放入st
        stat(html_file.c_str(), &st);

        //返回的时候， 还需要返回http的请求
        string http_response = "http/1.0 200 OK\n"; //状态行
        //正文部分的数据类型
        http_response += "Content-Type:text/html;charset=utf8\n";
        //正文长度
        http_response += "Content-Length:";
        http_response += to_string(st.st_size); // st.st_size就是正文长度
        http_response += "\n";                  //这个'\n'是正文长度结尾的'\n'，不是空行
        //空行
        http_response += "\n";

        //接下来是正文
        ifstream in(html_file);
        if (!in.is_open())
        {
            cerr << "open html error!" << endl;
        }
        else
        {
            string content;
            string line;
            //从in里读取数据放到line里面
            while (!getline(in, line))
            {
                content += line;
            }
            http_response += content;
            in.close();
            send(sock, http_response.c_str(), http_response.size(), 0);
        }
    }
    close(sock);
    return nullptr;
}

//./Http port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = atoi(argv[1]);

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    for (;;)
    {
        int sock = Sock::Accept(listen_sock);
        if (sock > 0)
        {
            pthread_t tid;
            int *pram = new int(sock);
            pthread_create(&tid, nullptr, HandlerHttpRequest, pram);
        }
    }

    return 0;
}